package com.cashmama.market.api.application.controller.risk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cashmama.market.api.application.annos.SignIgnore;
import com.cashmama.market.api.application.annos.VisitorAccessible;
import com.cashmama.market.api.application.controller.risk.request.RiskCallbackRequestParam;
import com.cashmama.market.api.domain.enums.UserRiskStatusEnum;
import com.cashmama.market.api.domain.service.ApiUserService;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.handler.ApiResponse;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.qianli.user.enums.UserAuthStatusEnum;
import com.qianli.user.facade.auth.UserAuthServiceFacade;
import com.qianli.user.ro.auth.UserAuthFirstRiskRO;
import com.qianli.user.ro.auth.UserPushRiskCallbackRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2020-05-15 17:15
 **/
@RestController
@RequestMapping("/risk")
public class RiskCallBackController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RiskCallBackController.class);

    @Autowired
    private UserAuthServiceFacade userAuthServiceFacade;
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @SignIgnore
    @VisitorAccessible
    @RequestMapping("/v1/callback")
    public ApiResponse riskCallBack(@RequestBody JSONObject request) {
        LOGGER.info("=============== 风控回调开始,request:{} ================", JSON.toJSONString(request));
        JSONObject data = request.getJSONObject("data");
        RiskCallbackRequestParam requestParam = JSON.parseObject(data.toJSONString(), RiskCallbackRequestParam.class);
        if (requestParam == null
                || StringUtils.isEmpty(requestParam.getTradeNo())
                || StringUtils.isEmpty(requestParam.getResultType())) {
            throw new ApplicationException("TradeNo or ResultType is empty");
        }
        if (Objects.equals(requestParam.getBizType(), "10003")) {
            String resultType = requestParam.getResultType();
            String tradeNo = requestParam.getTradeNo();
            UserPushRiskCallbackRequest userPushRiskRequest = new UserPushRiskCallbackRequest();
            userPushRiskRequest.setPushNo(tradeNo);
            userPushRiskRequest.setRiskResult(requestParam.getResult());
            Response<UserAuthFirstRiskRO> userAuthFirstRisk = userAuthServiceFacade.getUserAuthFirstRisk(tradeNo);
            if(userAuthFirstRisk.getData() != null && userAuthFirstRisk.getData().getRiskStatus() == UserAuthStatusEnum.SUCCESS.getCode()){
                return new ApiResponse("many times callback success");
            }
            if("all".equalsIgnoreCase(apolloConfigUtil.manualRiskResult())){
                if (UserRiskStatusEnum.PASSED.getCode().equals(resultType) || UserRiskStatusEnum.MANUAL.getCode().equals(resultType)) {
                    userPushRiskRequest.setRiskStatus(UserAuthStatusEnum.SUCCESS.getCode());
                } else if (UserRiskStatusEnum.REJECTED.getCode().equals(resultType)) {
                    userPushRiskRequest.setRiskStatus(UserAuthStatusEnum.REJECT.getCode());
                }
            }else{
                if("pass".equalsIgnoreCase(apolloConfigUtil.manualRiskResult())){
                    userPushRiskRequest.setRiskStatus(UserAuthStatusEnum.SUCCESS.getCode());
                }else{
                    userPushRiskRequest.setRiskStatus(UserAuthStatusEnum.REJECT.getCode());
                }
            }
            Response<Boolean> response = userAuthServiceFacade.firstRoundRiskCallBack(userPushRiskRequest);
            if(!response.isSuccess()){
                throw new ApplicationException(response.getMsg());
            }
            LOGGER.info("=============== 风控回调成功,request:{} ================", JSON.toJSONString(request));
            return new ApiResponse("callback success");
        } else {
            return new ApiResponse("it is not first round callback, pls check the logic is correct");
        }
    }
}
